/*
 * @Description: 登录页面
 * @Author: Zhanghan
 * @Date: 2025-02-21 09:07:52
 * @LastEditTime: 2025-07-24 15:08:38
 * @LastEditors: ZhangHan
 */
import { Button, Checkbox, Form, Input, message, notification } from "antd";
import { Local } from "@/enums/Local";
import { generateToken, getLocal, getToken, removeLocal } from "@/utils/token";
import { setInfo } from "@/store/features/user";
import { useDispatch, useSelector } from "react-redux";
import { useEffect } from "react";
import { userList } from "@/concacts/userList";
import { useNavigate } from "react-router-dom";
import type { FormProps } from "antd";
import useDisableDevTools from "@/hooks/useDisableDevTools";
import "./index.less";

function Login() {
  useDisableDevTools();
  const [messageApi, contextHolder] = message.useMessage();

  const myCleft = "c_left";
  const myCright = "c_right";

  type FieldType = {
    username?: string;
    password?: string;
  };

  const dispatch = useDispatch();
  const navigate = useNavigate();

  const userInfo = useSelector((state: any) => state?.user);

  useEffect(() => {
    const token = getToken();
    if (token) {
      const redirectPath =
        getLocal(Local.REDIRECT_PATH) ?? userInfo?.username === "user"
          ? "/shopList"
          : "/defaultPage";
      navigate(redirectPath, { replace: true });
    }
  }, []);

  const onFinish: FormProps<FieldType>["onFinish"] = (values) => {
    console.log("Success:", values);

    // person.greet();
    checkInfo(values);
  };

  const onFinishFailed: FormProps<FieldType>["onFinishFailed"] = (
    errorInfo
  ) => {
    console.log("Failed:", errorInfo);
  };

  //判断用户名密码是否正确
  const checkInfo = (value: FieldType) => {
    //用户名
    const userIndex = userList.findIndex(
      (item) => item.userName == value.username
    );
    if (userIndex == -1) {
      messageApi.open({
        type: "error",
        content: "用户名错误",
        duration: 1,
      });
      return;
    } else {
      const passwordIndex = userList.findIndex(
        (item) => item.password == value.password
      );
      if (passwordIndex == -1) {
        messageApi.open({
          type: "error",
          content: "密码错误",
          duration: 1,
        });
      } else {
        messageApi
          .open({
            type: "loading",
            content: "登录中",
            duration: 1.5,
          })
          .then(() => {
            messageApi
              .open({
                type: "success",
                content: "登录成功",
                duration: 1,
              })
              .then(() => {
                setTimeout(() => {
                  notification.success({
                    message: "登录成功",
                    description: "欢迎来到我们的系统",
                  });
                }, 500);
                handleLogin(value);
              });
              
          });
      }
    }
  };

  //登录
  const handleLogin = (value: FieldType) => {
    const token = generateToken(16);
    dispatch(setInfo({ token, username: value.username }));
    // 登录成功后
    const redirectPath = getLocal(Local.REDIRECT_PATH) || "/";
    removeLocal(Local.REDIRECT_PATH); // 清除路径
    if (value.username === "user") {
      return navigate("/shopList", { replace: true }); // 重定向
    }
    if (value.username === "zhuzhuxia") {
      return navigate("/personalBlog", { replace: true }); // 重定向
    }
    navigate(redirectPath, { replace: true }); // 重定向
  };

  return (
    <>
      {contextHolder}

      <div className="w-full h-full " style={{ background: "lightgray" }}>
        <div className="w-full h-full flex justify-center items-center">
          <div className="l_container">
            <div className="c_left">
              <div className={`${myCleft}-title`}>欢迎您的到来！</div>
              <div className={`${myCleft}-title`}>WELCOME !</div>
              <div className={`${myCleft}-desc`}>
                请在右侧输入账号密码，登录您的账号
              </div>
            </div>
            <div className="c_right">
              <div className={`${myCright}-title`}>请输入信息！</div>
              <div className={`${myCright}-form`}>
                <Form
                  name="basic"
                  labelCol={{ span: 8 }}
                  wrapperCol={{ span: 16 }}
                  style={{ maxWidth: 600 }}
                  initialValues={{ remember: true }}
                  onFinish={onFinish}
                  onFinishFailed={onFinishFailed}
                  autoComplete="off"
                >
                  <Form.Item<FieldType>
                    label="用户名："
                    name="username"
                    rules={[
                      {
                        required: true,
                        message: "请输入用户名称!",
                      },
                    ]}
                  >
                    <Input />
                  </Form.Item>

                  <Form.Item<FieldType>
                    label="密码："
                    name="password"
                    rules={[
                      {
                        required: true,
                        message: "请输入密码!",
                      },
                    ]}
                  >
                    <Input.Password />
                  </Form.Item>

                  <Form.Item label={null}>
                    <Button
                      className="sub_btn"
                      type="primary"
                      size="large"
                      htmlType="submit"
                    >
                      登录
                    </Button>
                  </Form.Item>
                </Form>
              </div>
            </div>
          </div>
        </div>
      </div>
    </>
  );
}

export default Login;
